<template>
  <!-- 角色管理 -->
  <div class="door">
    <el-form
      :inline="true"
      :model="elform"
      class="demo-form-inline"
      size="mini"
    >
      <el-form-item>
        <el-button
          type="primary"
          @click="roleAdd"
          size="mini"
          icon="el-icon-plus"
          v-if="isauth('atten_role_edit')"
          >添加</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="onExport"
          size="mini"
          icon="el-icon-document-copy"
          >导出</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 角色管理信息显示 -->
    <div class="my_table">
      <el-table
        v-loading="loading"
        :data="detailslist"
        ref="table"
        border
        highlight-current-row
        :header-cell-style="headFirst"
        :cell-style="(res) => headFirst_col(res, [])"
      >
        <!-- <el-table-column prop="pkRoleId" label="编号" align="center"></el-table-column> -->
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="200"
          v-if="isauth('atten_role_edit')"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="roleEdit(scope.row)" size="small"
              >角色人员管理</el-button
            >
            <el-button type="text" @click="role_Edit(scope.row)" size="small"
              >修改</el-button
            >
            <el-button
              type="text"
              @click.stop="deleteDate(scope.row.roleGuid)"
              size="small"
              style="color: red"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChangepage"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="recordCount"
        ></el-pagination>
      </div>
    </div>

    <!-- 添加角色信息 -->
    <el-dialog
      :before-close="addcloseDialog"
      width="500px"
      center
      title="添加角色信息"
      :close-on-click-modal="false"
      :visible.sync="addDialogFormVisible"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addForm"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-col :span="15">
            <el-input v-model="addForm.roleName" size="mini"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-col :span="15">
            <el-input v-model="addForm.remark" size="mini"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addvisible()">取消</el-button>
        <el-button type="primary" @click="addFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色信息 -->
    <el-dialog
      :before-close="editcloseDialog"
      width="500px"
      center
      title="修改角色信息"
      :close-on-click-modal="false"
      :visible.sync="editDialogFormVisible"
    >
      <el-form
        :model="editForm"
        :rules="addRules"
        ref="editForm"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-col :span="15">
            <el-input v-model="editForm.roleName" size="mini"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-col :span="15">
            <el-input v-model="editForm.remark" size="mini"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <span slot="footer" class="dialog-footer">
          <el-button @click="eidtvisible()">取消</el-button>
          <el-button type="primary" @click="eidtFormSubmit()">确定</el-button>
        </span>
      </span>
    </el-dialog>
    <div class="roleDialog">
      <!-- 角色角色人员管理 -->
      <el-dialog
        :before-close="eidtcloseDialog"
        width="900px"
        center
        title="角色人员管理"
        :close-on-click-modal="false"
        :visible.sync="eidtDialogFormVisible"
      >
        <div>
          <el-form :model="editForm" ref="editForm" class="demo-ruleForm">
            <el-form-item label="角色名称：" prop="roleName">
              <el-col :span="15">
                {{ editForm.roleName }}
                <!-- <el-input v-model="editForm.roleName" size="mini" disabled></el-input> -->
              </el-col>
            </el-form-item>
          </el-form>
          <el-button
            type="primary"
            @click="joinpeople"
            size="mini"
            style="margin-bottom: 10px"
            icon="el-icon-plus"
            >添加人员</el-button
          >
          <!-- <el-button
            type="primary"
            @click="addDepartmentPersonnel"
            size="mini"
            style="margin-bottom: 10px"
            icon="el-icon-plus"
            >填加整个部门人员</el-button
          > -->
          <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            :stripe="true"
            border
            :header-cell-style="headFirst"
            :cell-style="(res) => headFirst_col(res, [])"
          >
            <!-- <el-table-column type="selection" width="45" align="center"></el-table-column> -->
            <el-table-column
              prop="departmentName"
              label="部门"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="userName"
              label="姓名"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="userNumber"
              label="编号"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="cardNumber"
              label="卡号"
              align="center"
            ></el-table-column>
            <el-table-column prop="userSex" label="性别" align="center">
              <template slot-scope="scope">{{
                scope.row.userSex | userSexType
              }}</template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click.stop="deleteRole(scope.row.userGuid)"
                  size="small"
                  style="color: red"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div class="page">
            <el-pagination
              @size-change="RolehandleSizeChange"
              @current-change="RolehandleCurrentChangepage"
              :current-page.sync="RolecurrentPage"
              :page-sizes="[5, 10, 15]"
              :page-size="RolepageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="RolerecordCount"
            ></el-pagination>
          </div>
        </div>
      </el-dialog>
    </div>
    <!-- 房间人员加入弹窗 -->
    <add-room-jon
      v-if="addroomjonVisible"
      ref="addroomjoin"
      @refreshDataList="refreshDataList"
    ></add-room-jon>

    <add-dep-jon
      v-if="adddepjonVisible"
      ref="adddepjoin"
      @refreshDataList="addDepartment"
    ></add-dep-jon>
  </div>
</template>
<script>
import bus from '@/bus.js'
import AddRoomJon from '@/components/room-personnel-add-join'
import AddDepJon from '@/components/department-personnel-add-join'
export default {
  data() {
    return {
      // 角色添加弹窗
      addDialogFormVisible: false,
      // 角色修改
      editDialogFormVisible: false,
      addForm: {
        roleName: '',
        remark: '',
      },
      addRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
      },
      // 修改用户信息
      editForm: {
        roleName: '',
        remark: '',
      },
      // 当前需要修改角色的信息
      editRoleInfo: {},
      // 角色中的人员信息
      tableData: [],
      // 角色角色人员管理弹框
      eidtDialogFormVisible: false,

      // 加入人员弹窗
      addroomjonVisible: false,

      // 导出表格名称
      filename: '考勤角色信息',
      elform: {},

      // 房间号信息
      roomName: '',
      // 姓名/编号/卡号信息
      userName: '',
      loading: false,
      // 角色信息
      detailslist: [],
      pageNum: 1,
      pageSize: 10,
      currentPage: 1,
      recordCount: 0,
      // 角色里面的人员分页
      RolepageNum: 1,
      RolepageSize: 10,
      RolecurrentPage: 1,
      RolerecordCount: 0,
      searchInfo: {},
      /**加入整个部门的人 */
      adddepjonVisible: false,
    }
  },
  components: {
    AddRoomJon,
    AddDepJon,
  },
  filters: {
    userSexType(val) {
      if (val == 0) {
        return '男'
      } else if (val == 1) {
        return '女'
      }
    },
  },
  computed: {
    changeschoolid: {
      get() {
        return this.$store.state.user.changeschoolid
      },
    },
  },
  watch: {},
  created() {
    this.userGuid = sessionStorage.getItem('administrator')
  },
  mounted() {
    this.onSubmit()
  },
  methods: {
    // 将整部部门的人员加入该角色
    addDepartmentPersonnel() {
      console.log('部门')
      this.adddepjonVisible = true
      this.$nextTick(() => {
        this.$refs.adddepjoin.addinit('')
      })
    },
    // 确定后触发
    addDepartment(val) {
      console.log(val)
        // 批量加载条
      this.loadingZ = this.Loading.service({
        lock: true,
        text: '正在添加人员中，请稍等...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // 角色手下的人员添加
      this.$http({
        url: this.$http.adornUrl('/attendance/attendance-user-bind-role'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            attendanceRoleGuid: this.editRoleInfo.roleGuid,
            unitGuid: this.changeschoolid,
            departmentGuidList: val,
          },
          messageType: 0,
        }),
      }).then(({ data }) => {
        this.loadingZ.close();
        if (data.messageCode == 200) {
          this.$message({
            message: '已将选中部门中人员全部添加角色',
            type: 'success',
          })
          this.getRolePeople()
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 加入人员弹窗
    joinpeople() {
      this.addroomjonVisible = true
      console.log(this.editRoleInfo)
      this.$nextTick(() => {
        this.$refs.addroomjoin.addinit("/attendance/attendance-user-by-role-list",{'roleGuid':''})
      })
    },
    // 加入人员点击确定后触发
    refreshDataList(val) {
      this.addroomjonVisible = false
      console.log(this.editRoleInfo)
      if (val.length > 0) {
        this.setRolePeople(val)
      }
      console.log(val)
    },
    // 角色角色人员管理
    rolePersonnelEdit() {},

    // 查询角色
    onSubmit() {
      let searchInfo = {}
      searchInfo.unitGuid = this.changeschoolid
      this.$http({
        url: this.$http.adornUrl('/attendance/attendance-role-page'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            asc: true,
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchInfo: searchInfo,
          },
          messageType: 0,
        }),
      }).then(({ data }) => {
        console.log(data)
        if (data.messageCode == 200) {
          // this.$message({
          //   message: "查询成功",
          //   type: "success"
          // });
          this.recordCount = data.messageContent.recordCount
          this.detailslist = data.messageContent.data
          console.log(data.messageContent.data)
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 导出数据需要用到的
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    // 导出
    onExport() {
      if (this.recordCount == 0) {
        this.$message({
          message: '无数据可导出',
          type: 'warning',
        })
        return false
      }
      let searchInfo = {}
      searchInfo.unitGuid = this.changeschoolid
      this.$http({
        url: this.$http.adornUrl('/attendance/attendance-role-page'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            asc: true,
            pageNum: 1,
            pageSize: this.recordCount,
            searchInfo: searchInfo,
          },
          messageType: 0,
        }),
      }).then(({ data }) => {
        console.log(data)
        if (data.messageCode == 200) {
          let detailslist = data.messageContent.data
          require.ensure([], () => {
            let multiHeader = []
            let merges = []
            let tHeader = ['角色名称']
            let filterValArr = ['roleName']
            const { export_json_to_excel } = require('../../excel/Export2Excel')
            const filterVal = filterValArr
            const list = detailslist
            const data = this.formatJson(filterVal, list)
            export_json_to_excel({
              multiHeader,
              header: tHeader,
              data,
              merges,
              filename: this.filename + this.getimeto(),
              tableheader: '1',
            })
          })
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.onSubmit()
    },
    handleCurrentChangepage(val) {
      this.pageNum = val
      this.onSubmit()
    },
    // 删除模板
    deleteDate(roleGuid) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.roleDel(roleGuid)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 删除
    roleDel(roleGuid) {
      console.log(roleGuid)
      this.$http({
        url: this.$http.adornUrl('/attendance/attendance-role-delete'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            roleGuid,
            unitGuid: this.changeschoolid,
          },
          messageType: 0,
        }),
      }).then(({ data }) => {
        console.log(data)
        if (data.messageCode == 200) {
          this.$message({
            message: '删除成功',
            type: 'success',
          })
          console.log(this.pageNum)
          this.pageNum = this.currentPage
          this.onSubmit()
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 添加
    roleAdd() {
      this.addDialogFormVisible = true
      this.addForm.roleName = ''
    },
    // 添加关闭
    addcloseDialog(done) {
      done()
    },
    // 角色修改
    role_Edit(row) {
      this.editRoleInfo = row
      this.$set(this.editForm, 'roleName', row.roleName)
      this.editDialogFormVisible = true
    },
    // 角色修改关闭
    editcloseDialog(done) {
      this.editDialogFormVisible = false
      done()
    },
    // 取消添加
    addvisible() {
      this.addDialogFormVisible = false
    },
    // 确定添加
    addFormSubmit() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/attendance/attendance-role-add'),
            method: 'post',
            data: this.$http.adornData({
              messageContent: {
                roleName: this.addForm.roleName,
                unitGuid: this.changeschoolid,
                remark: this.addForm.remark,
              },
              messageType: 0,
            }),
          }).then(({ data }) => {
            console.log(data)
            if (data.messageCode == 200) {
              this.$message({
                message: '添加成功',
                type: 'success',
              })
              this.onSubmit()
              this.addDialogFormVisible = false
            } else {
              this.$message.error(data.errorMessage)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 修改
    roleEdit(row) {
      // 当前修改的角色信息
      this.editRoleInfo = row
      this.$set(this.editForm, 'roleName', row.roleName)
      this.RolepageNum = 1
      this.getRolePeople()
      this.eidtDialogFormVisible = true
    },
    eidtcloseDialog(done) {
      this.eidtDialogFormVisible = false
      done()
    },
    // 取消修改
    eidtvisible() {
      this.editDialogFormVisible = false
    },
    // 确定修改
    eidtFormSubmit() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/attendance/attendance-role-update'),
            method: 'post',
            data: this.$http.adornData({
              messageContent: {
                roleGuid: this.editRoleInfo.roleGuid,
                roleName: this.editForm.roleName,
                remark: this.editForm.remark,
                unitGuid: this.changeschoolid,
              },
              messageType: 0,
            }),
          }).then(({ data }) => {
            console.log(data)
            if (data.messageCode == 200) {
              this.$message({
                message: '修改成功',
                type: 'success',
              })
              this.onSubmit()
              this.editDialogFormVisible = false
            } else {
              this.$message.error(data.errorMessage)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 角色手下的人员添加
    setRolePeople(val) {
       // 批量加载条
      this.loadingZ = this.Loading.service({
        lock: true,
        text: '正在添加人员中，请稍等...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.$http({
        url: this.$http.adornUrl('/attendance/attendance-user-bind-role'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            attendanceRoleGuid: this.editRoleInfo.roleGuid,
            unitGuid: this.changeschoolid,
            userGuidList: val,
          },
          messageType: 0,
        }),
      }).then(({ data }) => {
        this.loadingZ.close()
        console.log(data)
        if (data.messageCode == 200) {
          this.$message({
            message: '添加成功',
            type: 'success',
          })
          this.getRolePeople()
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 角色手下人员查询
    getRolePeople() {
      this.$http({
        url: this.$http.adornUrl('/attendance/attendance-user-by-role-page'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            asc: true,
            pageNum: this.RolepageNum,
            pageSize: this.RolepageSize,
            searchInfo: {
              roleGuid: this.editRoleInfo.roleGuid,
              unitGuid: this.changeschoolid,
            },
          },
          messageType: 0,
        }),
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          this.tableData = data.messageContent.data || []
          this.RolerecordCount = data.messageContent.recordCount
          this.RolecurrentPage = data.messageContent.pageNum
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 角色手下的人员删除
    deleteRole(userGuid) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/attendance/attendance-user-unbind-role'),
            method: 'post',
            data: this.$http.adornData({
              messageContent: {
                roleGuid: this.editRoleInfo.roleGuid,
                unitGuid: this.changeschoolid,
                userGuidList: [userGuid],
              },
              messageType: 0,
            }),
          }).then(({ data }) => {
            console.log(data)
            if (data.messageCode == 200) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              this.getRolePeople()
            } else {
              this.$message.error(data.errorMessage)
            }
          })
        })
        .catch(() => {})
    },
    // 角色里面的人员分页
    RolehandleSizeChange(val) {
      this.RolepageSize = val
      this.getRolePeople()
    },
    RolehandleCurrentChangepage(val) {
      this.RolepageNum = val
      this.getRolePeople()
    },
  },
}
</script>

<style lang="scss" scoped>
.door {
  padding: 10px;
}
.page {
  display: flex;
  justify-content: center;
  align-items: center;
}

.TimeWeek {
  padding: 20px 0 0;
}
.roleDialog {
  .el-form-item {
    margin-bottom: 0;
  }
  /deep/.el-dialog--center .el-dialog__body {
    padding: 20px;
    padding-top: 0;
  }
}

// 隐藏纵向滚动条
</style>